package com.ruoyi.app.service.imp;

import com.ruoyi.app.service.IPromotionCodeService;
import com.ruoyi.business.domain.JtAppUser;
import com.ruoyi.business.domain.JtUserPromotionCodeRel;
import com.ruoyi.business.service.IJtAppUserService;
import com.ruoyi.business.service.IJtUserPromotionCodeRelService;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @Author Alan Zhang
 * @Date 2025/6/13 14:43
 */
@Service
public class PromotionCodeServiceImp implements IPromotionCodeService {
    @Autowired
    protected IJtAppUserService jtAppUserService;
    @Autowired
    protected IJtUserPromotionCodeRelService jtUserPromotionCodeRelService;

    /**
     * 绑定推广码
     * @param promotionCode 推广码
     * @return
     */
    @Override
    public AjaxResult promotionBindUser(JtAppUser jtAppUser, @NotNull String promotionCode){
        //邀约码
        JtAppUser param = new JtAppUser();
        param.setPromotionCode(promotionCode);
        List<JtAppUser> appUserList = jtAppUserService.selectJtAppUserList(param);
        if(appUserList.size() == 0){
            return AjaxResult.error("用户推广码，不存在！");
        }
        JtAppUser jtAppUserOwner = appUserList.get(0);
        //邀约关系
        JtUserPromotionCodeRel relParam = new JtUserPromotionCodeRel();
        relParam.setPromotionCode(jtAppUser.getPromotionCode());
        List<JtUserPromotionCodeRel> promotionCodeRelList = jtUserPromotionCodeRelService.selectJtUserPromotionCodeRelList(relParam);
        if(promotionCodeRelList.size() > 0){
            return AjaxResult.error("该用户推广码，已被邀请！");
        }

        JtUserPromotionCodeRel entity = new JtUserPromotionCodeRel();
        entity.setPromotionCode(jtAppUser.getPromotionCode());
        entity.setOwnerUserId(jtAppUserOwner.getUserId());
        entity.setUserId(jtAppUser.getUserId());
        entity.setCreateBy(promotionCode);
        entity.setUpdateBy(jtAppUserOwner.getUserName());
        int rows = jtUserPromotionCodeRelService.insertJtUserPromotionCodeRel(entity);
        if(rows > 0){
            return AjaxResult.success("用户："+jtAppUserOwner.getUserName()+" 推广码："+promotionCode+"，邀请成功！");
        } else {
            return AjaxResult.error("用户："+jtAppUserOwner.getUserName()+" 推广码："+promotionCode+"，邀请失败！");
        }
    }
}
